package com.rr.middle;

import java.util.*;

/**
 * @author RR
 * @date 2024/1/13 19:28
 */
public class RepeatLimitedString {
    public String repeatLimitedString(String s, int repeatLimit) {
        int[] counts = new int[26];
        Set<Character> charactersSet = new TreeSet<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            charactersSet.add(c);
            counts[c-97]++;
        }
        StringBuilder builder = new StringBuilder();
        Character[] characters = charactersSet.toArray(new Character[0]);
        buildStr(counts, characters, characters.length-1, repeatLimit, builder);
        return builder.toString();
    }

    private void buildStr(int[] counts, Character[] characters, int characterIndex, int repeatLimit, StringBuilder builder) {
        if (characterIndex == -1) {
            return;
        }
        int countIndex = characters[characterIndex] - 97;
        if (counts[countIndex] == 0) {
            buildStr(counts, characters, characterIndex - 1, repeatLimit, builder);
        }
        while (counts[countIndex] > 0) {
            if (counts[countIndex] > repeatLimit) {
                counts[countIndex] -= repeatLimit;
                for (int i = 0; i < repeatLimit; i++) {
                    builder.append(characters[characterIndex]);
                }
                // 前面没得借了，直接返回
                if (characterIndex == 0) {
                    return;
                }
                boolean has = false;
                for (int i = characterIndex-1; i >= 0; i--) {
                    if (counts[characters[i] - 97] > 0) {
                        counts[characters[i] - 97]--;
                        builder.append(characters[i]);
                        has = true;
                        break;
                    }
                }
                if (!has) {
                    return;
                }
            } else {
                for (int i = 0; i < counts[countIndex]; i++) {
                    builder.append(characters[characterIndex]);
                }
                counts[countIndex] = 0;
                buildStr(counts, characters, characterIndex - 1, repeatLimit, builder);
            }
        }
    }

    public static void main(String[] args) {
        RepeatLimitedString solution = new RepeatLimitedString();
        String s = solution.repeatLimitedString("mapzhptjmudmgdutgqcyscceybfzyqmmmmbdkgzssqnfyoxmebniribeubudsegsflsvhcgbhvzhjb", 6);
        System.out.println(s);
    }
}
